import type { CreateDeck } from '/@/api/currentDeck/model/deckModel';
import { computed, defineComponent, toRaw, unref } from 'vue';
import { appShareUsing } from '/@/utils/appInteractive';
import { useGo } from '/@/hooks/web/usePage';
import { awaitWrap, getTokenUrl } from '/@/utils';
import { useMessage } from '/@/hooks/web/useMessage';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import Title from '/@/views/general/components/Title';
import { Icon } from '/@/components/Icon';
import { Button, Field } from 'vant';
import DeckSelectedCardList from '/@/views/currentDeck/components/DeckSelectedCardList';
import { DeckDetailApi, ModifyDeckApi, CreateDeckApi } from '/@/api/currentDeck/deck';

import('./index.less');

export default defineComponent({
  name: 'CurrentDeckCreatePage',
  props: {
    deckId: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    // 设置分享参数
    appShareUsing({} as any);

    const { createLoadingToast, clearToast } = useMessage();
    const currentStore = useCurrentDeckStore();
    const go = useGo();

    const pageTile = computed(() => {
      const { deckId } = props;
      if (deckId) {
        return '修改套牌';
      }
      return '创建套牌';
    });
    const leftClick = () => {
      const { deckId } = props;
      currentStore.clearCreateDeckParams();
      if (deckId) {
        go(`/currentdeckdetail/${deckId}`, true);
        return;
      }
      go(getTokenUrl(`/currentdeck/${currentStore.gameId}`), true);
    };

    const getDeckDetail = async () => {
      if (!props.deckId) {
        !currentStore.createDeckParams.deck_name ? (currentStore.createDeckParams.deck_name = '我的套牌') : null;
        return false;
      }
      const [error, result] = await awaitWrap(DeckDetailApi({ deck_id: Number(props.deckId) }));
      if (error || !result) {
        return;
      }
      // 如果在详情页面已经获取到数据就不在赋值
      !currentStore.createDeckParams.deck_name ? (currentStore.createDeckParams.deck_name = result.deck_name) : null;
      currentStore.createDeckParams.deck_desc = result.deck_desc;
      currentStore.createDeckParams.is_open = result.is_open || 0;
      currentStore.createDeckParams.tags = result.tags || [];
      if (currentStore.getCreateDeckParams.deck_id) {
        return;
      }
      !currentStore.getCreateDeckParams.deck_info.length ? currentStore.setDeckInfo(result.deck_info) : null;
    };
    getDeckDetail();

    const inputSlot = {
      'left-icon': () => {
        return <Icon icon={'ri:edit-2-fill'} />;
      },
    };

    const confirm = () => {
      createLoadingToast({
        message: '保存中',
        overlay: true,
      });
      props.deckId ? modifyDeck() : createCard();
    };

    const modifyDeck = async () => {
      const result = toRaw(currentStore.getCreateDeckParams) as CreateDeck;
      result.deck_name ? null : (result.deck_name = '我的套牌');
      result.deck_id = Number(props.deckId);
      const [error] = await awaitWrap(ModifyDeckApi(result));
      if (error) {
        clearToast();
        return;
      }
      clearToast();
      currentStore.clearCreateDeckParams();
      go(`/currentdeckdetail/${props.deckId}`, true);
    };

    const createCard = async () => {
      const result = toRaw(currentStore.getCreateDeckParams);
      result.deck_name ? null : (result.deck_name = '我的套牌');
      const [error] = await awaitWrap(CreateDeckApi(result));
      if (error) {
        clearToast();
        return;
      }
      clearToast();
      currentStore.clearCreateDeckParams();
      go(getTokenUrl(`/currentdeck/${currentStore.gameId}`), true);
    };

    return () => (
      <div class={'current-deck-create-page'}>
        <Title title={unref(pageTile)} leftArrow onLeftClick={leftClick} />
        <div class={'create-container'}>
          <div class={'flex deck-name'}>
            <div class={'input-item justify-between mr-lg'}>
              <Field
                label={'套牌名称'}
                v-slots={inputSlot}
                labelClass={'input-label'}
                clearable
                v-model={[currentStore.getCreateDeckParams.deck_name]}
              ></Field>
            </div>
          </div>
          <DeckSelectedCardList deckCardList={currentStore.getCreateDeckParams.deck_info} titleColor={true} />
        </div>
        <ul class={'action-area flex items-center justify-center'}>
          <li
            class={'addcard flex-1 flex justify-center items-center'}
            onClick={() => {
              go('/currentdeckcard');
            }}
          >
            <Icon class={'!text-xl mr-md'} icon={'carbon:add-filled'} />
            <span>添加/修改单卡</span>
          </li>
          <li>
            <Button type={'success'} block size={'large'} class={'!px-lg'} onClick={confirm}>
              {props.deckId ? '确认修改' : '确认创建'}
            </Button>
          </li>
        </ul>
      </div>
    );
  },
});
